<?php

namespace app\api\controller;

use app\common\controller\Api;
use think\Db;
use app\api\model\Activity;
use app\api\model\Coupon;
use think\Log;
use think\Request;
use wxpay\lspay;
use alipay\Alipay;
use fast\Http;
use epay\epay;
use Monolog\Handler\DynamoDbHandler;

/**
 * 首页接口
 */
class ThreePay extends Api
{
    protected $noNeedLogin = ['notifyx'];
    protected $noNeedRight = ['*'];
    //支付费用
    public function payJoinfee($name, $ooid, $price)
    {
        $s = Db::table('box_setting')->where('id', 1)->find();
        $mch_id = $s['lspay_mch_no'];
        $key = $s['lspay_key'];
        $app_id = $s['lspay_app_id'];
        $openid = $this->auth->wx_mini_openid;
        $notifyurl = $this->request->domain() . '/index.php/api/three_pay/notifyx';
        $weixinpay = new lspay($openid, $mch_id, $key, $app_id, $name, $ooid, $price, $notifyurl);
        $return = $weixinpay->pay();
        $this->success('支付', ['data' => $return, 'ooid' => $ooid]);
    }
    /**
     * 开盲盒支付
     */
    public function goPay()
    {
        $post = input('post.');
        // $ooid = 'ALDMH' . date('Ymd') . substr(implode('', array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
        list($msec, $sec) = explode(' ', microtime());
        $num = md5(floatval($msec) + floatval($sec).time());
        $ooid = 'ALDMH' . date('Ymd') . substr(md5(implode('', array_map('ord', str_split(substr(uniqid(), 7, 13), 1))).$num), 0, 8);
        $box = Db::table('box_boxfl')->where('id', $post['boxid'])->find();
        if(empty($box)){
            $this->error('盲盒不存在');
        }
        $data = [
            'boxfl_id' => $post['boxid'],
            'boxfl_name' => $box['box_name'],
            'image' => $box['box_banner_images'],
            'num' => $post['num'],
            'user_id' => $this->auth->id,
            'pay_method' => $post['payfs'],
            'pay_coin' => $post['price'],
            'out_trade_no' => $ooid,
            'status' => 'unpay', //unpay=待支付,used=已使用,refund=已关闭
            'create_time' => time(),
            'terminal' => $post['terminal'],
            'xingshi' => $post['xs'],
            'ischou' => 0,
        ];
        $oid = Db::table('box_order')->insertGetId($data);
        if(!$oid){
            $this->error("订单添加失败");
        }
        /**
         * 判断来源
         * 0：H5
         * 1：小程序
         * 2：APP
         */
        if ($post['terminal'] == 0) {
            //如果为0就是H5
            $epay = new epay;
            if ($post['payfs'] == 'alipay') {
                $notifyurl = $this->request->domain() . '/index.php/api/pay/epaymhnotifyx';
                $epay->goePay($ooid, 'alipay', '软件服务费', $post['price'],$notifyurl,$this->request->domain() . '/h5/#/pages/home/luckbox?ooid='.$ooid . '&num='.$post['num'].'&boxid='.$post['boxid']);
            }else if($post['payfs'] == 'wechat'){
                $notifyurl = $this->request->domain() . '/index.php/api/pay/epaymhnotifyx';
                $epay->goePay($ooid, 'wechat', '软件服务费', $post['price'],$notifyurl,$this->request->domain() . '/h5/#/pages/home/luckbox?ooid='.$ooid . '&num='.$post['num'].'&boxid='.$post['boxid']);
            }
        } else if ($post['terminal'] == 1) {
            // 如果为1就是小程序---这里只有微信支付了
            if($post['price'] < 0){
                $this->error("金额出错，请联系管理员");
            }elseif ($post['price'] == 0){
                self::handle($ooid,0);
                $this->success('支付成功',['ooid'=>$ooid]);
            }
            $this->payJoinfee('软件服务费', $ooid, $post['price']);

        } else if ($post['terminal'] == 2) {
            //如果为2就是APP
            $alipay = new Alipay();
            $notice = $this->request->domain() . '/index.php/api/pay/mhnotifyx';
            $alipay->pay('软件服务费', $ooid, $post['price'], $notice);
        }
    }
    public function notifyx()
    {
        $testxml = file_get_contents("php://input");
        $jsonxml = json_encode(simplexml_load_string($testxml, 'SimpleXMLElement', LIBXML_NOCDATA));
        $result = json_decode($jsonxml, true); //转成数组，
        if ($result) {
            //如果成功返回了
            $out_trade_no = $result['out_trade_no'];
            $transaction_id = $result['transaction_id'];
            $this->handle($out_trade_no, $transaction_id);
        }
        log::write(["msg"=>"微信回调成功","userid"=>$this->auth->id,"out_trade_no"=>$result['out_trade_no']],"log");
        $xml = '<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>';
        echo $xml;
    }
    //订单处理
    public function handle($ooid, $tranid)
    {
        $ret = Db::table('box_order')->where('out_trade_no', $ooid)->update(['status' => 'used', 'pay_time' => time(), 'transaction_id' => $tranid]);
        $order = Db::table('box_order')->where('out_trade_no', $ooid)->find();
        $s = Db::table('box_setting')->where('id', 1)->find();
        $user = Db::table('box_user')->where('id', $order['user_id'])->find();
        // Db::table('box_moneylog')
        if (!empty($ret)) {
            log::write(['msg'=>"回调成功",'data'=>$ret],'error');
            $this->getOne($order,$user);
            if ($order['xingshi'] != '0') {
                $res = Db::table('box_user')->where('id', $order['user_id'])->update(['money' => $user['money'] - $order['xingshi']]);
                log::write(['msg'=>"抵扣成功了吗？",'data'=>$res],'error');
                Db::table('box_moneylog')->insert([
                    'user_id' => $order['user_id'],
                    'beforemoney' => $user['money'],
                    'aftermoney' => ($user['money'] - $order['xingshi']) <= 0 ? 0 :  ($user['money'] - $order['xingshi']),
                    'money' => $order['xingshi'],
                    'bgexplain' => 'dikou',
                    'addtime' => time()
                ]);
            }
            if (!empty($user['pid']) && $order['pay_coin'] > 0) {
                //处理返佣,被邀请人首次开盒，赠送上级星石
                //1.查找是否是第一次开盒
                $count = Db::table('box_order')->where('user_id', $user['id'])->count();
                if ($count == 1){
                    $u = Db::table('box_user')->where('id', $user['pid'])->find();
                    //2.根据后台设置返佣比例返佣,星石：金额=10:1
                    $addStone = $order['pay_coin'] * ($s['pid_get_stone']/100) * 10;
                    $res = Db::table('box_user')->where('id', $user['pid'])->setInc('money', $addStone);
                    if (!empty($res)) {
                        Db::table('box_detailed')->insert([
                            'user_id' => $user['pid'],
                            'lytag' => 'kaihe',
                            'lxtag' => 'stone',
                            'stone' => $addStone,
                            'laiyuan' => '好友首次开盒奖励' . $addStone .'星石',
                            'jltime' => time()
                        ]);
                        Db::table('box_moneylog')->insert([
                            'user_id' => $u['id'],
                            'beforemoney' => $u['money'],
                            'aftermoney' => $u['money'] + $addStone,
                            'money' => $addStone,
                            'bgexplain' => 'pidback',
                            'addtime' => time()
                        ]);
                    }
                }
            }
        }
    }
}
